import request from '@/utils/request'

/**
 * 从响应中解析 houseId
 * @param {*} resp - API响应数据
 * @returns {number|undefined} 解析出的 houseId 或 undefined
 */
export function extractHouseIdFromResponse(resp) {
  const v1 = resp?.data?.data
  if (Number.isFinite(Number(v1))) return Number(v1)
  
  const v2 = resp?.data
  if (Number.isFinite(Number(v2))) return Number(v2)
  
  const v3 = resp
  if (Number.isFinite(Number(v3))) return Number(v3)
  
  console.warn('[houseId] 无法从响应中解析 houseId:', resp)
  return undefined
}

/**
 * 获取房源列表（支持筛选）
 */
export const getHouseListApi = ({
  houseId,
  title,
  rentType,
  status,
  cityId,
  communityName,
  pageNo,
  pageSize
}) => {
  return request({
    method: 'post',
    url: '/admin/house/list',
    data: {
      houseId,
      title,
      rentType,
      status,
      cityId,
      communityName,
      pageNo,
      pageSize
    }
  })
}

/**
 * 获取城市列表
 */
export const getCityListApi = () => {
  return request({
    method: 'get',
    url: '/admin/map/city_list'
  })
}

/**
 * 获取房源详情
 */
export const getHouseDetailApi = (houseId) => {
  return request({
    method: 'get',
    url: '/admin/house/detail',
    params: {
      houseId
    }
  })
}

/**
 *修改房源状态（包含租期）
 */
export const putHouseStatusApi = ({
  houseId,
  status,
  rentTimeCode
}) => {
  return request({
    method: 'post',
    url: '/admin/house/status/edit',
    data: {
      houseId,
      status,
      rentTimeCode
    }
  })
}

/**
 * 获取子行政区划
 */
export const getChildrenRegionApi = (parentId) => {
  return request({
    method: 'get',
    url: '/admin/map/region_children_list',
    params: {
      parentId
    }
  })
}

/**
 * 图片上传
 */
export const postImageUploadApi = (formData) => {
  return request({
    method: 'post',
    url: '/file/upload',
    data: formData
  })
}

/**
 * 新增/修改房源（仅 houseId 透传，其他字段不动）
 */
export const postHouseApi = ({
  houseId, // ✅ 新增：可选
  title,
  cityId,
  regionId,
  communityName,
  detailAddress,
  rentType,
  rooms,
  floor,
  allFloor,
  area,
  position,
  userId,
  price,
  houseType,
  intro,
  tagCodes,
  devices,
  images,
  headImage,
  cityName,
  regionName,
  longitude,
  latitude
}) => {
  const data = {
    title,
    cityId,
    regionId,
    communityName,
    detailAddress,
    rentType,
    rooms,
    floor,
    allFloor,
    area,
    position,
    userId,
    price,
    houseType,
    intro,
    tagCodes,
    devices,
    images,
    headImage,
    cityName,
    regionName,
    longitude,
    latitude
  }
  
  // 仅当为有效数字时注入 houseId
  const hid = Number(houseId)
  if (Number.isFinite(hid)) {
    data.houseId = hid
  }
  
  return request({
    method: 'post',
    url: '/admin/house/add_edit',
    data
  })
}
